<script setup lang="jsx">
import { reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { Button, Tag } from 'ant-design-vue';
import { parseTime } from '@/utils';
import { deleteDictItem, exportDict, getDictItemlistData, optionselect } from '@/service/api';
import Modal from '@/components/common/modal.vue';
import { useRouterPush } from '@/hooks/common/router';
import { useTabStore } from '@/store/modules/tab';
import { useRouteStore } from '@/store/modules/route';
import AddForm from './modules/add.vue';
import Search from './modules/search.vue';

const { routerPushByKey } = useRouterPush();
const tabStore = useTabStore();
const routeStore = useRouteStore();
const route = useRoute();

const props = defineProps({
  id: {
    type: String,
    default: () => null
  }
});

const searchParams = ref({
  dictLabel: null,
  dictTypes: Number(props.id),
  status: null
});

const dictTypeList = ref([]);
function getSelectList() {
  optionselect().then(({ data, error }) => {
    if (!error) {
      dictTypeList.value = data;
      getDictName(searchParams.value.dictTypes);
      getData();
    }
  });
}
getSelectList();

const pagination = reactive({
  current: 1,
  pageSize: 200,
  showSizeChanger: true,
  pageSizeOptions: ['50', '100', '200', '300', '500'],
  showQuickJumper: true,
  showTotal: total => {
    return `共${total}条`;
  },
  total: 0,
  onChange: async (current, size) => {
    pagination.current = current;
    pagination.pageSize = size;
    getData();
  }
});

const columns = ref([
  {
    key: 'dictCode',
    dataIndex: 'dictCode',
    title: '字典编码',
    align: 'center',
    width: 150,
    checked: true,
    ellipsis: true
  },
  {
    key: 'dictLabel',
    dataIndex: 'dictLabel',
    title: '字典标签',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return record.dictLabel;
    }
  },
  {
    key: 'dictValue',
    dataIndex: 'dictValue',
    title: '字典键值',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'dictSort',
    dataIndex: 'dictSort',
    title: '字典排序',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'status',
    dataIndex: 'status',
    title: '状态',
    align: 'center',
    width: 150,
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.status === null) {
        return null;
      }

      const tagMap = {
        0: 'success',
        1: 'error'
      };

      const label = record.status == 0 ? '正常' : '停用';

      return <Tag color={tagMap[record.status] || 'error'}>{label}</Tag>;
    }
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: '备注',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'createTime',
    dataIndex: 'createTime',
    title: '创建时间',
    align: 'center',
    checked: true,
    width: 170,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.createTime == null) {
        return null;
      }
      return parseTime(record.createTime);
    }
  },
  {
    key: 'cz',
    dataIndex: 'createTime',
    title: '操作',
    align: 'center',
    width: 200,
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return (
        <div>
          <Button type="link" size="small" onClick={() => add('edit', record)}>
            <icon-ic-round-edit class="align-sub text-icon" />
            修改
          </Button>
          <Button
            type="link"
            size="small"
            danger
            v-if={record.parentId !== 0}
            onClick={() => {
              del(record);
            }}
          >
            <icon-ic-round-delete class="align-sub text-icon" />
            删除
          </Button>
        </div>
      );
    }
  }
]);
const tableData = ref([]);
const loading = ref(false);
const dictType = ref(null);
function getData() {
  loading.value = true;
  const { dictLabel, dictTypes, status } = searchParams.value;
  if (dictTypes) {
    dictType.value = dictTypeList.value?.find(item => item.dictId === dictTypes)?.dictType || null;
  }
  const params = {
    dictLabel,
    status,
    dictType: dictType.value,
    pageSize: pagination.pageSize,
    pageNum: pagination.current
  };
  getDictItemlistData(params)
    // .then(({ data, error }) => {
    //     if (!error) {
    //       pagination.total = data?.total || 0;
    //       tableData.value = data.rows;
    //     }
    // })
    .then( res => {
      console.log('res :>> ', res);
      const data = res.otherData;
      if (data.code === 200) {
        pagination.total = data?.total || 0;
        tableData.value = data.rows;
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

const dictName = ref(null);
function getDictName(type) {
  dictName.value = dictTypeList.value.find(item => item.dictId === type).dictName;
}

function search() {
  pagination.current = 1;
  getData();
}

const currentRowId = ref(null);
const customRow = record => {
  return {
    style: {
      // 'background-color': record.dictCode === currentRowId.value ? 'rgba(86, 205, 243, 0.3)' : ''
    },
    class: record.dictCode === currentRowId.value ? 'jl-table-row-selected' : '',
    onClick: () => {
      currentRowId.value = record.dictCode;
    }
  };
};

const selectedRowKeys = ref([]);

function tableSelectChange(val) {
  selectedRowKeys.value = val;
}

function del(row) {
  let dictId = '';
  if (row) {
    dictId = row.dictCode;
  } else {
    dictId = selectedRowKeys.value.join();
  }
  window.$modal.confirm({
    title: `是否确认删除字典编号为"${dictId}"的数据项？`,
    onOk: () => {
      deleteDictItem(dictId).then(({ error }) => {
        if (!error) {
          window.$message.success('删除成功');
          getData();
        }
      });
    }
  });
}

const currentRow = ref(null);
const operateType = ref('add');
const visible = ref(false);
const addFormRef = ref(null);
function add(type, row = null) {
  if (typeof row === 'number') {
    row = tableData.value.find(item => item.postId == row);
  }
  currentRow.value = row;
  operateType.value = type;
  visible.value = true;
}

function handleOk() {
  addFormRef.value.submitForm();
}

function handleClose() {
  visible.value = false;
  currentRow.value = null;
}

function handleSuccess() {
  getData();
  handleClose();
}

function downloadExcel() {
  const params = {
    ...searchParams.value,
    pageSize: pagination.pageSize,
    pageNum: pagination.current
  };
  exportDict(params);
}

async function closePage() {
  const path = route.fullPath;
  const tab = tabStore.tabs.find(item => {
    if (item.fullPath === path) {
      return item;
    }
  });
  await tabStore.removeTab(tab.id);
  await routerPushByKey('manage_dict');
  await routeStore.reCacheRoutesByKey(tab.routeKey);
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search
      v-model:model="searchParams"
      :dict-type-list="dictTypeList"
      @reset="search()"
      @search="search()"
      @dict-types-change="getDictName"
    />
    <ACard
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="table-card flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #title>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="add('add')">
          <template #icon>
            <icon-ic-round-add class="align-sub text-icon" />
          </template>
          <span class="ml-3px">新增</span>
        </AButton>
        <AButton
          danger
          size="small"
          ghost
          class="mini-btn mr-8px"
          :disabled="selectedRowKeys.length == 0"
          @click="del()"
        >
          <template #icon>
            <icon-ic-round-delete class="align-sub text-icon" />
          </template>
          <span class="ml-3px">删除</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="downloadExcel">
          <template #icon>
            <icon-ic-round-download class="align-sub text-icon" />
          </template>
          <span class="ml-3px">导出</span>
        </AButton>
        <AButton type="primary" ghost class="mini-btn mr-8px" @click="closePage">
          <template #icon>
            <icon-ic-round-close class="align-sub text-icon" />
          </template>
          <span class="ml-3px">关闭</span>
        </AButton>
      </template>
      <template #extra>
        <TableColumnSetting v-model:columns="columns" />
      </template>
      <ATable
        :columns="columns"
        :data-source="tableData"
        size="small"
        :loading="loading"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: tableSelectChange }"
        row-key="dictCode"
        :default-expand-all-rows="true"
        :scroll="{ x: 'auto', y: 'auto' }"
        :pagination="pagination"
        :custom-row="customRow"
        :row-height="33"
        class="h-full"
      />
    </ACard>

    <Modal
      v-model:visible="visible"
      :title="`${operateType == 'add' ? '新增' : '修改'}字典数据`"
      height="675px"
      width="650px"
      :destroy-on-close="true"
      @ok="handleOk"
      @close="handleClose"
    >
      <AddForm
        ref="addFormRef"
        :current-row="currentRow"
        :operate-type="operateType"
        :dict-type="dictType"
        :dict-name="dictName"
        @success="handleSuccess"
      />
      <template #footer>
        <div class="modal-footer">
          <AButton type="primary" @click="handleOk()">确定</AButton>
          <AButton @click="handleClose">取消</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style></style>
